﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.Eventing.Reader;
using System.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Web.Mvc;
using AutoMapper;
using NC.Data;
using NC.ViewModels;
using NC.Models;
using PagedList;
using Recaptcha;

namespace NC.Controllers
{
    public class PostController : Controller
    {
        //private readonly AccountController _accountController;
        private readonly PostRepository _postRepository;
        private readonly AddressRepository _addressRepository;

        public PostController()
        {
           // _accountController = new AccountController();
            _postRepository = new PostRepository();
            _addressRepository = new AddressRepository();
        }

        /// <summary>
        /// This returns CreatePost page
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateNewPost()
        {
            return View("CreateNewPost");
        }
        [HttpGet]
        public JsonResult LoadDDLCountry()
        {
            var countryList = _addressRepository.GetAllCountries();
            var countryData = countryList.Where(x=> !x.Id.Equals(NcConstants.DefaultCountryId)).Select(m => new SelectListItem()
            {
                Text = m.CountryName,
                Value = m.Id.ToString(),
            });
            return Json(countryData, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// Load the states by country id dropdownlist
        /// </summary>
        /// <param name="countryId">Country ID</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult LoadDDLStates(string countryId)
        {
            int stateID = Convert.ToInt32(countryId);
            var stateList = _addressRepository.GetStateByCountryId(stateID);

            var stateData = stateList.Select(m => new SelectListItem()
            {
                Text = m.StateName,
                Value = m.Id.ToString(),

            });

            return Json(stateData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadDDLCity(string stateId)
        {
            int cityID = Convert.ToInt32(stateId);
            var cityList = _addressRepository.GetCityByStateId(cityID);

            var cityData = cityList.Select(m => new SelectListItem()
            {
                Text = m.CityName,
                Value = m.Id.ToString(),

            });

            return Json(cityData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public JsonResult LoadDDLCategory(string id)
        {
            //int cityID = Convert.ToInt32(id);
            var catList = _postRepository.GetAllPostCategories();

            var catData = catList.Select(m => new SelectListItem()
            {
                Text = m.CategoryName,
                Value = m.Id.ToString(),

            });

            return Json(catData, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult CreatePost()
        {
            if (TempData["nc"] != null)
            { ViewBag.check = "1"; }
            return View();
        }

        [HttpPost]
        public JsonResult CreatePost(CreatePost post)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { success = false, result = "Validation Error" }, JsonRequestBehavior.AllowGet);
            }

            Post postModel = new Post
            {
                Needed = post.Needed == "1",
                CategoryId = post.CategoryID,
                Title = post.Title,
                Description = post.Description,
                PostDate = DateTime.Now,
                ShowEmailInPost = post.ShowEmailInPost,
                ContactPhone = post.ContactPhone,
                LocationId = SaveAddress(post),
                CreatorName = post.PostCreatorName,
                ContactEmail = post.PostCreatorEmail
            };
            postModel = Mapper.Map<Post>(_postRepository.SaveNewPost(postModel));
            UrlHelper redirectUrl = new UrlHelper(ControllerContext.RequestContext);
            string url = redirectUrl.Action("SinglePost", "Post", new { postId = postModel.Id });
            return Json(new { success = true, redirectToUrl = url }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public ActionResult CreatePostWithEmail(string email)
        {
            var createPostModel = (CreatePost)Session["CreatePostModel"];
            var accountUser = new NC.Models.AccountUserModel {Email = email};
            accountUser.GeneratePassword();
            //_accountController.RegisterAccount(accountUser);
            CreatePost(createPostModel);
            return null;
        }

        [HttpGet]
        public ActionResult SinglePost(int postId)
        {
            int id = Convert.ToInt32(Request.QueryString["postId"]);
            var singlepost = Mapper.Map<Post>(_postRepository.GetPostById(id));
            return View(singlepost);
        }       

        public ActionResult Categories()
        {
            IList<Category> categories = _postRepository.GetAllPostCategories().OrderBy(x=> x.CategoryName).ToList();
            categories.Add(new Category(){CategoryName = "All", Id = 0});
            return PartialView(categories);
        }

        public ActionResult Locations()
        {
            IList<Address> addresses =
                _postRepository.GetAllLocations().GroupBy(x => x.State.Id).Select(y => y.First()).ToList();
            return PartialView(addresses);
        }

        public ActionResult Subcription()
        {
            Subcribe sc = new Subcribe {Category = _postRepository.GetAllPostCategories()};
            return PartialView(sc);
        }

        [HttpGet]
        public PartialViewResult ReplyToAPost()
        {
            return PartialView();
        }

        [RecaptchaControlMvc.CaptchaValidator]
        public JsonResult ReplyToAPost(bool captchaValid, ReplyPost replyPostModel)
        {
            try
            {
                RecaptchaValidator va = new RecaptchaValidator();
                va.Validate();
                if (captchaValid)
                {
                    return Json(new { success = "other" });
                }
                else
                {
                    var mailMessage = replyPostModel.GetReplyToAPostMessage();
                    var email = new Email(mailMessage);
                    email.Send();
                    return Json(new { success = "true" });
                }
            }
            catch (Exception)
            {
                return Json(new { success = "false" });
            }
        }

        private int SaveAddress(CreatePost post)
        {
            //Create address object and save it to table and assign its id to the postmodel's locationid
            Address address = new Address
            {
                CityId = Int32.Parse(post.City),
                StateId = Int32.Parse(post.State),
                CountryId = Int32.Parse(post.Country),
                ZipCode = Int32.Parse(post.ZipCode ?? NcConstants.DefaultZipCodeId)
            };
            return _addressRepository.SaveAddress(address);
        }

        [HttpGet]
        public ActionResult ViewNeededPosts(int page = 1, int categoryId = 0, int stateId = 0, string stateName = "")
        {
            var posts = categoryId == 0 ? _postRepository.GetAllNeededPosts() : _postRepository.GetNeededPostsByCategory(categoryId);
            if (stateId != 0)
            {
                posts = posts.Where(x => x.Address.State.Id == stateId).ToList();
            }
            if (stateName != "")
            {
                IList<Post> newPosts = new List<Post>();
                foreach (var post in posts)
                {
                    if (MinimumEditDistance.Levenshtein.CalculateDistance(stateName, post.Address.State.StateName, 1) <
                        6)
                    {
                        newPosts.Add(post);
                    }
                }
                return PartialView(newPosts.ToPagedList(page, NcConstants.DefaultNumberOfPostsInAPage));
            }
            return PartialView(posts.ToPagedList(page, NcConstants.DefaultNumberOfPostsInAPage));
        }

        [HttpGet]
        public ActionResult ViewAvailablePosts(int page = 1, int categoryId = 0, int stateId = 0, string stateName = "")
        {
            var posts = categoryId == 0 ? _postRepository.GetAllAvailablePosts() : _postRepository.GetAvailablePostsByCategory(categoryId); 
            if (stateId != 0)
            {
                posts = posts.Where(x => x.Address.State.Id == stateId).ToList();
            }
            if (stateName != "")
            {
                IList<Post> newPosts = new List<Post>();
                foreach (var post in posts)
                {
                    if (MinimumEditDistance.Levenshtein.CalculateDistance(stateName, post.Address.State.StateName, 1) <
                        3)
                    {
                        newPosts.Add(post);
                    }
                }
                return PartialView(newPosts.ToPagedList(page, NcConstants.DefaultNumberOfPostsInAPage));
            }
            return PartialView(posts.ToPagedList(page, NcConstants.DefaultNumberOfPostsInAPage));
        }
    }
}